package org.jtzc.springaifunction.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Set;

@RestController
public class FunctionController {

    @Autowired
    private ChatModel chatModel;

    @Autowired
    private FunctionCallback functionCallback;

    @GetMapping(value = "/function",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public String function01(@RequestParam("userMessage") String userMessage) {
        return ChatClient.builder(chatModel)
                .build().prompt()
                .system("""
                    您是算术计算器的代理。
                    您能够支持加法运算、乘法运算等操作，其余功能将在后续版本中添加，如果用户问的问题不支持请告知详情。
                    在提供加法运算、乘法运算等操作之前，您必须从用户处获取如下信息：两个数字，运算类型。
                    请调用自定义函数执行加法运算、乘法运算。
                    请讲中文。
                    """)
                .user(userMessage)
                .functions("addOperation", "mulOperation")
                .call()
                .content();
    }




    @GetMapping("/fc")
    public Object functionCall(@RequestParam String location) {
        UserMessage userMessage = new UserMessage(location);
        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .model("gpt-4o")
                .functions(Set.of("currentTime"))
                .build();
        Prompt prompt = new Prompt(List.of(userMessage), options);
        ChatResponse response = chatModel.call(prompt);

        return response;
    }

    @GetMapping("/fc-stream")
    public Flux<ChatResponse> functionStreamCall(@RequestParam String location) {
        UserMessage userMessage = new UserMessage(location);
        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .model("gpt-4o")
                .functions(Set.of("currentTime"))
                .streamUsage(true)
                .build();
        Prompt prompt = new Prompt(List.of(userMessage), options);
        Flux<ChatResponse> stream = chatModel.stream(prompt);
        return stream;
    }
}
